//
//  MineController.m
//  RentTable
//
//  Created by mac on 2024/11/28.
//

#import "MineController.h"
#import "MineTabCell.h"
#import "ShopController.h"
#import "ShopCollectController.h"
#import "FeedbackPopupView.h"
#import "AppDelegate.h"

@interface MineController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UILabel *phoneLabel;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *options;
@property (nonatomic, strong) UIImageView *avartImageview;

@end

@implementation MineController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self loadData];
    [self setUI];
}

- (void)loadData {
    self.options = @[
        @[@"购物车",@"购物车"],@[@"我的收藏",@"我的收藏"],@[@"客服",@"在线客服"],@[@"意见反馈",@"意见反馈"],
        @[@"退出登录",@"退出登录"],@[@"注销登录",@"注销登录"],@[@"登陆",@"登陆"]
        
    ];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
    NSString *account = [LocalDataManager loadDataForKey:UserAccount];
    NSString *logStau = [LocalDataManager loadDataForKey:LogStatu];
    
    if (account && [logStau isEqualToString:@"LogIn"]) {
        self.nameLabel.text = @"咖喱巧克力";
        NSString *userIphone = [LocalDataManager loadDataForKey:UserAccount];
        self.phoneLabel.text = userIphone;
        self.avartImageview.image = [UIImage imageNamed:@"头像男孩"];
    }else {
        self.nameLabel.text = @"未登录";
        self.phoneLabel.text = @"未登录";
        self.avartImageview.image = [UIImage imageNamed:@"头像"];
    }
}

- (void)setUI {
    UIImageView *playImageView = [UIImageView new];
    [playImageView setUserInteractionEnabled:true];
    playImageView.image = [UIImage imageNamed:@"我的-bg"];
    [self.view addSubview:playImageView];
    [playImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    NSString *userIphone = [LocalDataManager loadDataForKey:UserAccount];
    self.nameLabel = [[UILabel alloc] init];
    
    self.nameLabel.text = @"咖喱巧克力";
    self.nameLabel.font = [UIFont pingFangSCMediumWithSize:18];
    self.nameLabel.textColor = myRGBHex(0x333333);
    [self.view addSubview:self.nameLabel];
    
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(207 * scaleH);;
        make.leading.mas_equalTo(20);
        make.height.mas_equalTo(22 * scaleH);
    }];
    
    self.phoneLabel = [[UILabel alloc] init];
    self.phoneLabel.text = userIphone;
    self.phoneLabel.font = [UIFont pingFangSCRegularWithSize:12];
    self.phoneLabel.textColor = myRGBHex(0x333333);
    [self.view addSubview:self.phoneLabel];
    
    [self.phoneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameLabel.mas_bottom).offset(4 * scaleH);
        make.leading.mas_equalTo(20);
        make.height.mas_equalTo(16 * scaleH);
    }];
    
    UIImageView *avartImageview = [UIImageView new];
    avartImageview.image = [UIImage imageNamed:@"头像男孩"];
    [self.view addSubview:avartImageview];
    [avartImageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(203 * scaleH);
        make.trailing.mas_equalTo(-20);
        make.size.mas_equalTo(CGSizeMake(48, 48));
    }];
    self.avartImageview = avartImageview;
    
    UIView *mineBackView = [UIView new];
    mineBackView.backgroundColor = myRGBHex(0xFFFFFF);
    mineBackView.frame = CGRectMake(16, 280 * scaleH, spDeviceWidth - 16, spDeviceHeight - 344 * scaleH);
    [self.view addSubview:mineBackView];
    [mineBackView setCornerRadius:20 forCorners:UIRectCornerTopLeft borderColor:myRGBHex(0xFFFFFF) borderWidth:0.0];
    
    [self setupCollectionview:mineBackView];
}

- (void)setupCollectionview:(UIView *)backView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemSize = CGSizeMake(85 * scaleW, 73 * scaleH);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 16;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[MineTabCell class] forCellWithReuseIdentifier:@"MineTabCell"];
    
    [backView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(22 * scaleH);
        make.leading.mas_equalTo(7);
        make.trailing.mas_equalTo(-7);
        make.height.mas_equalTo(180 * scaleH);
    }];
}

#pragma mark - UICollectionView DataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.options.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MineTabCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MineTabCell" forIndexPath:indexPath];
    NSArray *itemData = self.options[indexPath.row];
    [cell setTableData:itemData];
    
    return cell;
}

#pragma mark - UICollectionView Delegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *account = [LocalDataManager loadDataForKey:UserAccount];
    NSString *logStau = [LocalDataManager loadDataForKey:LogStatu];
    
    if (indexPath.row == 0) {
        if (account && [logStau isEqualToString:@"LogIn"]) {
            ShopController *vc = [ShopController new];
            vc.hidesBottomBarWhenPushed = true;
            [self.navigationController pushViewController:vc animated:false];
        }else {
            [QLToast makeToast:@"请先登陆" toView:self.view];
        }
        
        
    }else if (indexPath.row == 1) {
        
        if (account && [logStau isEqualToString:@"LogIn"]) {
            ShopCollectController *vc = [ShopCollectController new];
            vc.hidesBottomBarWhenPushed = true;
            [self.navigationController pushViewController:vc animated:false];
        }else {
            [QLToast makeToast:@"请先登陆" toView:self.view];
        }
        
    }else if (indexPath.row == 2) {
        
        [self showAlert];
    }else if (indexPath.row == 3) {
        
        [self showFeedbackPopup];
    }else if (indexPath.row == 4) {
        
        
        [self showLogout2ConfirmationWithCompletion:^(BOOL confirmed) {
            if (confirmed) {
                [LocalDataManager saveData:@"LogOut" forKey:LogStatu];//头像
                self.avartImageview.image = [UIImage imageNamed:@"头像"];
                self.nameLabel.text = @"未登录";
                self.phoneLabel.text = @"未登录";
                [QLToast makeToast:@"退出登录成功" toView:self.view];
            } else {
                // 用户选择了“否”，执行取消操作
                NSLog(@"用户取消注销账户");
            }
        }];
        
    }else if (indexPath.row == 5) {
        
        NSString *logStau = [LocalDataManager loadDataForKey:LogStatu];
        if ([logStau isEqualToString:@"LogOut"]) {
            [QLToast makeToast:@"请先登陆" toView:self.view];
            return;
        }
        
        [self showLogoutConfirmationWithCompletion:^(BOOL confirmed) {
            if (confirmed) {
                // 用户选择了“是”，执行注销操作
                [LocalDataManager saveData:WithdrawAccount forKey:WithdrawAccount];
                [LocalDataManager removeDataForKey:UserAccount];
                [LocalDataManager removeDataForKey:UserPassword];
                self.avartImageview.image = [UIImage imageNamed:@"头像"];
                self.nameLabel.text = @"--";
                self.phoneLabel.text = @"--";
                [QLToast makeToast:@"注销账号成功" toView:self.view];
            } else {
                // 用户选择了“否”，执行取消操作
                NSLog(@"用户取消注销账户");
            }
        }];
        
        
        
    }else if (indexPath.row == 6) {
        if (account && [logStau isEqualToString:@"LogIn"]) {
            [QLToast makeToast:@"你已经是登陆状态" toView:self.view];
            return;
        }
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        [appDelegate goToLogin];
    }
    
}

- (void)showAlert {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"联系客服"
                                                                             message:@"联系方式：2550978987（QQ）"
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    
    UIView *alertContentView = alertController.view.subviews.firstObject.subviews.firstObject;
    alertContentView.layer.cornerRadius = 15.0f;
    
    CGRect frame = alertContentView.frame;
    frame.size.height = 190;
    alertContentView.frame = frame;
    
    UIAlertAction *copyAction = [UIAlertAction actionWithTitle:@"复制"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * _Nonnull action) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = @"2550978987（QQ）";
        NSLog(@"复制按钮 tapped");
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消按钮 tapped");
    }];
    
    [alertController addAction:copyAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)showFeedbackPopup {
    FeedbackPopupView *feedbackPopup = [[FeedbackPopupView alloc] initWithFrame:self.view.bounds];
    
    [self.view addSubview:feedbackPopup];
}

- (void)showLogoutConfirmationWithCompletion:(void (^)(BOOL confirmed))completion {
    // 创建 UIAlertController 弹框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"是否注销账户"
                                                                             message:@"账户注销，资料不可恢复，请谨慎选择"
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"否"
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {
        if (completion) {
            completion(NO);
        }
    }];
    
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"是"
                                                            style:UIAlertActionStyleDestructive
                                                          handler:^(UIAlertAction * _Nonnull action) {
        
        if (completion) {
            completion(YES);
        }
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)showLogout2ConfirmationWithCompletion:(void (^)(BOOL confirmed))completion {
    // 创建 UIAlertController 弹框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"退出登录"
                                                                             message:@"是否退出登录?"
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"否"
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {
        if (completion) {
            completion(NO);
        }
    }];
    
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"是"
                                                            style:UIAlertActionStyleDestructive
                                                          handler:^(UIAlertAction * _Nonnull action) {
        
        if (completion) {
            completion(YES);
        }
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [self presentViewController:alertController animated:YES completion:nil];
}



@end
